package com.jams.goodox.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.jams.goodox.R;
import com.jams.goodox.utils.ToastUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Jin on 2016/6/22.
 * Description 带clear的EditText
 */
public class SyllabearEditText extends RelativeLayout {

	private EditText inputBox;
	private ImageView clear;

	// 文本改变监听器
	private SyllabearTextWatcher watcher;

	// 初始化的editText的文本
	private String initText = "";

	private boolean hasChange = false;

	// 若为true   editText里面有内容时，变大变粗
	private boolean isStronger = false;
	private float textSize;

	// 是否按手机号码隔几个添加一个空格
	private boolean phoneBlank = false;

	public SyllabearEditText(Context context, AttributeSet attrs) {
		super(context, attrs);

		View view = View.inflate(context, R.layout.custom_view_syllabear, null);
		this.addView(view);

		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SyllabearEditText);

		try {
			// 控件的属性列表
			String hint = a.getString(R.styleable.SyllabearEditText_hint);
			int maxLength = a.getInteger(R.styleable.SyllabearEditText_maxLength, 999);
			int defaultSize = getResources().getDimensionPixelSize(R.dimen.font_size_content);
			textSize = a.getDimension(R.styleable.SyllabearEditText_txtSize, defaultSize);
			int inputType = a.getInteger(R.styleable.SyllabearEditText_inputType, 0);
			isStronger = a.getBoolean(R.styleable.SyllabearEditText_isStronger, false);
			phoneBlank = a.getBoolean(R.styleable.SyllabearEditText_phoneBlank, false);
			if (phoneBlank)
				maxLength += 2;

			clear = (ImageView) view.findViewById(R.id.clear);
			inputBox = (EditText) view.findViewById(R.id.inputBox);

			inputBox.setHint(hint);
			// 设置最大字数
			InputFilter[] filters = { new InputFilter.LengthFilter(maxLength) };
			inputBox.setFilters(filters);
			// 根据px设置字体大小
			inputBox.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
			setInputType(inputType);

			initView();
		} finally {
			a.recycle();
		}
	}

	private void initView() {
		inputBox.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (s.length() > 0) {
					hasChange = true;
					clear.setVisibility(View.VISIBLE);

					if (null != watcher) {
						if (s.toString().equalsIgnoreCase(initText)) {
							hasChange = false;
							watcher.onTextChanged(false);
						} else {
							watcher.onTextChanged(true);
						}
					}

					if (isStronger) {
						inputBox.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize + 3);
						TextPaint tp = inputBox.getPaint();
						tp.setFakeBoldText(true);
					}

					if (phoneBlank) {
						addBlank(s, start, before);
					}
				} else {
					clear.setVisibility(View.INVISIBLE);
					hasChange = false;

					if (null != watcher)
						watcher.onTextChanged(false);

					if (isStronger) {
						inputBox.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
						TextPaint tp = inputBox.getPaint();
						tp.setFakeBoldText(false);
					}
				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		clear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				inputBox.setText("");
				inputBox.requestFocus();
			}
		});
	}

	boolean isFirstInitEditText = true;

	/**
	 * 设置默认文本内容
	 * @param str 默认文本内容
	 */
	public void initEditText(String str) {
		if (isFirstInitEditText) {
			inputBox.setText(str);
			inputBox.setSelection(str.length());
			clear.setVisibility(View.VISIBLE);
			initText = str;
			isFirstInitEditText = false;
		}
	}

	public boolean isNoChange() {
		return initText.equalsIgnoreCase(getText());
	}

	public void addSyllabearTextWatcher(SyllabearTextWatcher watcher) {
		this.watcher = watcher;
	}

	/**
	 *
	 * @return 当文本为空 或者 和 @initEditText 方法中初始文本一样  则返回false
	 */
	public boolean hasChange() {
		return true;
	}

	public String getText() {
		if (phoneBlank)
			return inputBox.getText().toString().replace(" ", "");
		return inputBox.getText().toString();
	}

	public interface SyllabearTextWatcher {
		/**
		 * 文本改变监听器
		 * @param hasChange 当文本为空 或者 和 @initEditText 方法中初始文本一样  则返回false
		 */
		void onTextChanged(boolean hasChange);
	}

	/**
	 * 修改输入类型
	 * @param inputType 输入类型 SyllabearTextType
	 */
	public void setInputType(int inputType) {

		switch (inputType) {
			case 0:
				inputBox.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
				break;
			case 1:
				inputBox.setInputType(InputType.TYPE_CLASS_PHONE);
				break;
			case 2:
				inputBox.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				break;
			case 3:
				inputBox.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
				break;
		}
	}

	/*********规则判定*******/
	public boolean conformToRules(Context context) {
		if (lengthJudge) {
			if (getText().length() < min || getText().length() > max) {
				ToastUtil.showShort(context, msgLength);
				return false;
			}
		}
		if (txtJudge) {
			if (!txtJudge()) {
				if (!txtJudgeMsg.equalsIgnoreCase(""))
					ToastUtil.showShort(context, txtJudgeMsg);
				return false;
			}
		}
		return true;
	}

	// 是否启用文本长度判断
	private boolean lengthJudge = false;
	private int min = 0;
	private int max = 999999;
	// 自定义长度错误toast信息
	private String msgLength = "";

	/**
	 * 字数上下限制
	 * @param min min
	 * @param max max
	 * @param msg 打印文本
	 */
	public void setLimitLength(int min, int max, String msg) {
		lengthJudge = true;
		this.min = min;
		this.max = max;
		this.msgLength = msg;
	}

	// 是否启用文本判断
	private boolean txtJudge = false;
	// 文本类型
	private int txtType;
	// 自定义错误toast信息
	private String txtJudgeMsg = "";
	// 保证只能第一次的设置生效
	private boolean hasSetTxtJudge = false;

	/**
	 * 设置文本输入类型
	 * @param textType 文本输入类型
	 */
	public void setTextType(int textType, String msg) {
		if (hasSetTxtJudge)
			return;
		txtJudge = true;
		this.txtType = textType;
		this.txtJudgeMsg = msg;
		hasSetTxtJudge = true;
	}

	public boolean txtJudge() {
		boolean result = true;
		switch (txtType) {
			case SyllabearTextType.TYPE_ENGLISH:
				result = justEnglish();
				break;
			case SyllabearTextType.TYPE_ENGLISH_CHINESE:
				result = justEnglishAndChinese();
				break;
			case SyllabearTextType.TYPE_ENGLISH_CHINESE_NUMBER:
				result = hasNoneSpecial();
				break;
			case SyllabearTextType.TYPE_ENGLISH_NUMBER:
				result = justEnglishAndNumber();
				break;
			case SyllabearTextType.TYPE_PHONE:
				result = isPhoneNum();
				break;
		}
		return result;
	}

	/**
	 * 中英文和数字
	 * @return 有特殊字符返回true
	 */
	private boolean hasNoneSpecial() {
		return getText().matches("[a-zA-Z0-9\u4e00-\u9fa5]*");
	}

	/**
	 * 只有中英文
	 * @return 只是中英文就返回true
	 */
	private boolean justEnglishAndChinese() {
		return getText().matches("[a-zA-Z\u4e00-\u9fa5]*");
	}

	/**
	 * 只有英文数字
	 * @return 只是英文数字就返回true
	 */
	private boolean justEnglishAndNumber() {
		return getText().matches("[a-zA-Z0-9]*");
	}

	/**
	 * 只有英文
	 * @return 只是英文就返回true
	 */
	private boolean justEnglish() {
		return getText().matches("[a-zA-Z0-9]*");
	}
	/**
	 * 判断是否是手机号码
	 * @return 是否是电话号码格式
	 */
	private boolean isPhoneNum() {
		String phone = getText();
		if (TextUtils.isEmpty(phone)) {
			return false;
		} else {
			Pattern phoMat = Pattern.compile("[1][3-9]{1}[0-9]{9}");
			Matcher matcher = phoMat.matcher(phone);
			return matcher.matches();

		}
	}

	private void addBlank(CharSequence s, int start, int before) {
		if (s == null || s.length() == 0) return;
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			if (i != 3 && i != 8 && s.charAt(i) == ' ') {
				continue;
			} else {
				sb.append(s.charAt(i));
				if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
					sb.insert(sb.length() - 1, ' ');
				}
			}
		}
		if (!sb.toString().equals(s.toString())) {
			int index = start + 1;
			if (sb.charAt(start) == ' ') {
				if (before == 0) {
					index++;
				} else {
					index--;
				}
			} else {
				if (before == 1) {
					index--;
				}
			}
			inputBox.setText(sb.toString());
			inputBox.setSelection(index);
		}
	}

}
